package com.apache.portal.service.plugin;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.AnntationBean;
import com.apache.portal.common.enums.NetMethodEnum;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.*;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xhe
 * 对接农E通服务端NetService插件
 */
@AnntationBean(name = "net")
public class NetSystemPluginImpl implements PortalPlugin {

    private Logger log = LoggerFactory.getLogger(NetSystemPluginImpl.class);

    /* (non-Javadoc)
     * @see com.apache.portal.plugin.PortalPlugin#doInvoke(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.Map)
     */
    public Object doInvoke(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        String doCode = params.get("doCode");
        LoginUser loginUser = PortalPubFactory.getInstance().getLoginUser(request);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.putAll(params);
        ResultEntity entity = new ResultEntity();

        switch (NetMethodEnum.getName(doCode)) {
        case proList://标的列表
            //			paramsMap.put("userCname", String.valueOf(request.getParameter("userCname")));
            paramsMap = toMapDelNull(paramsMap);
            //调用RPC
            entity = (ResultEntity) getRpcResult("proList", paramsMap);
            break;
        case proListAll://标的列表(带PUB信息)
            entity = (ResultEntity) getRpcResult("proListAll", paramsMap);
            break;
        case proInfo://获取项目信息
            entity = (ResultEntity) getRpcResult("proInfo", paramsMap);
            break;
        case proSave://保存成交信息
            entity = savePro(request, loginUser, paramsMap);
            break;
        case proEdit://项目信息修改
            entity = editPro(request, loginUser, paramsMap);
            break;
        case proStartFlow://启动项目流程
            entity = proStartFlow(request, loginUser, paramsMap);
            break;
        case proEntity://获取项目信息(pro,pub,info)
            entity = (ResultEntity) getRpcResult("proEntity", paramsMap);
            break;
        case sellerList://获取成交列表
            paramsMap.put("userType", "seller");
            entity = (ResultEntity) getRpcResult("userList", paramsMap);
            break;
        case dealList://获取成交列表
            entity = (ResultEntity) getRpcResult("dealList", paramsMap);
            break;
        case dealSave://保存成交信息
            entity = saveDeal(request, loginUser, paramsMap);
            break;
        case baoMing://提交报名登记
            entity = baoMing(request, loginUser, paramsMap);
            break;
        case applyList://查询报名信息列表
            entity = (ResultEntity) getRpcResult("applyList", paramsMap);
            break;
        case applyInfo://获取报名信息
            entity = (ResultEntity) getRpcResult("applyInfo", paramsMap);
            break;
        case regBrandPro://挂牌
            entity = (ResultEntity) getRpcResult("regBrandPro", paramsMap);
            break;
        case pickBrandPro://摘牌
            entity = (ResultEntity) getRpcResult("pickBrandPro", paramsMap);
            break;
        case transUserSave://保存transUser信息
            entity = (ResultEntity) getRpcResult("userSave", paramsMap);
            break;
        case transUserEdit://修改transUser信息
            entity = (ResultEntity) getRpcResult("userEdit", paramsMap);
            break;
        case transUserInfo://获取transUser信息
            entity = (ResultEntity) getRpcResult("userInfo", paramsMap);
            break;
        case applyEdit://修改apply信息
            entity = (ResultEntity) getRpcResult("applyEdit", paramsMap);
            break;
        case sendInvoice://生成保证金划入凭单
            entity = (ResultEntity) getRpcResult("sendInvoice", paramsMap);
            break;
        case bailOut://生成退保凭单
            entity = (ResultEntity) getRpcResult("bailOut", paramsMap);
            break;
        case billIn://生成价款划入单据
            entity = buildBillIn(request, response, paramsMap);
            break;
        case billOut://生成价款划出单据
            entity = buildBillOut(request, paramsMap);
            break;
        case settleFlowList://获取结算业务流水列表
            entity = (ResultEntity) getRpcResult("settleFlowList", paramsMap);
            break;
        case settleFlowEntity://获取结算业务流水信息
            entity = (ResultEntity) getRpcResult("settleFlowEntity", paramsMap);
            break;
        case settleBillList://获取结算凭单列表
            entity = (ResultEntity) getRpcResult("settleBillList", paramsMap);
            break;
        case settleBillEntity://获取结算凭单信息
            entity = (ResultEntity) getRpcResult("settleBillEntity", paramsMap);
            break;
        case billPay://结算凭单支付提交
            entity = (ResultEntity) getRpcResult("billPay", paramsMap);
            break;
        case billPayBelow://结算凭单支付提交-线下
            entity = (ResultEntity) getRpcResult("billPay", paramsMap);
            break;
        case auditSave://通用审核方法
            entity = (ResultEntity) getRpcResult("auditSave", paramsMap);
            break;
        case auditList://通用审核方法
            entity = (ResultEntity) getRpcResult("auditList", paramsMap);
            break;
        case pubEdit://修改规则信息
            entity = (ResultEntity) getRpcResult("pubEdit", paramsMap);
            break;
        case dymicSql://
            entity = (ResultEntity) getRpcResult("dymicSql", paramsMap);
            break;
        case testDymicSql://
            entity = (ResultEntity) getRpcResult("dymicSql", paramsMap);
            break;
        case saveCred://生成交易凭证
            entity = (ResultEntity) getRpcResult("saveTransBill", paramsMap);
            break;
        case delTransBill://删除交易凭证
            entity = (ResultEntity) getRpcResult("delTransBill", paramsMap);
            break;
        case transBillInfo://查看凭证信息
            entity = (ResultEntity) getRpcResult("transBillInfo", paramsMap);
            break;
        case transBillList://查看凭证信息列表
            entity = (ResultEntity) getRpcResult("transBillList", paramsMap);
            break;
        case editBillStatus://修改凭单状态
            /* 参数:dealId/billId
             * 状态：bill_status,pay_status,dealStatus
             * 当传dealId时,执行方向:userType(buyer,seller),默认为buyer
             * */
            entity = (ResultEntity) getRpcResult("editBillStatus", paramsMap);
            break;
        case dealInfo://获取成交deal信息
            entity = (ResultEntity) getRpcResult("dealInfo", paramsMap);
            break;
        case billCashier://价款出纳
            entity = (ResultEntity) getRpcResult("billCashier", paramsMap);
            break;
        case editBillInOut://凭单调用钱包转移资金
            entity = (ResultEntity) getRpcResult("editBillInOut", paramsMap);
            break;
        case pushBid://推送信息到竞价系统
            entity = (ResultEntity) getRpcResult("pushBid", paramsMap);
            break;

        case cateInfo:
            entity = (ResultEntity) getRpcResult("cateInfo", paramsMap);
            break;
        }
        return entity;
    }

    /**
     * description:  报名提交
     * 1.提交后台报名apply保存，
     * 2.启动报名意向登记流程；
     * 3.初始化审核audit表数据；
     */
    private ResultEntity baoMing(HttpServletRequest request, LoginUser loginUser,
            Map<String, Object> paramsMap) {
        String proId = String.valueOf(paramsMap.get("proId"));
        ResultEntity entity = (ResultEntity) getRpcResult("baoMingApply", paramsMap);
        if (null == entity.getEntity()) {
            ResultEntity entity2 = new ResultEntity();
            entity2.setResult("false");
            entity2.setMessage("没有获取到项目成交信息");
            return entity;
        }
        if (null != entity.getEntity()) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap = (Map<String, Object>) entity.getEntity();
            //初始化审核表
            auditInit(proId, "trp_apply", "apply_id", String.valueOf(resultMap.get("applyId")),
                    String.valueOf(paramsMap.get("userEname")),
                    String.valueOf(resultMap.get("applyAuditId")), "意向登记流程初始化");
        }
        return entity;
    }

    /**
     * description:  生成价款划入单据
     * params参数说明：
     * proPriceAmount：价款,buyerFeeAmount：受让方服务费,bailPriceAmout:有效保证金
     * settleUserNo:钱包账号,payType:支付方式
     * sellBankUserName：付/收款方开户账户名称,sellBankName：付/收款方开户行名称
     * sellBankNo：付/收款方开户行行号, sellBankAdr：付/收款方开户行地址
     * buyerId:受让方ID,buyerEname:受让方ename,buyerName:受让方名称
     * proId,dealId
     */
    private ResultEntity buildBillIn(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> paramsMap) {
        String proId = String.valueOf(paramsMap.get("proId"));
        String proNo = String.valueOf(paramsMap.get("proNo"));
        DataMap result = null;
        if (ToolsUtil.isNull(proId)) {
            ResultEntity entity = new ResultEntity();
            entity.setResult("false");
            entity.setMessage("缺少方法执行参数");
            return entity;

        }
        String clientIp = RequestTools.getIp(request);
        String sysPass = ConfigUtil.getInstance().interfacePass();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("sysPass", sysPass);
        data.put("proId", proId);
        data.put("proNo", proNo);
        data.put("Client-IP", clientIp);
        ResultEntity entity = getRpcResult("dealList", data);
        if (null == entity.getEntity()) {
            ResultEntity entity2 = new ResultEntity();
            entity2.setResult("false");
            entity2.setMessage("没有获取到项目成交信息");
            return entity;
        }
        List<Map> list = (List) entity.getEntity();
        for (Map map : list) {
            data.clear();
            data.put("Client-IP", clientIp);
            data.put("sysPass", sysPass);
            data.put("proId", proId);
            data.put("dealId", String.valueOf(map.get("dealId")));
            data.put("proPriceAmount", String.valueOf(map.get("settlePrice")));
            data.put("buyerFeeAmount", String.valueOf(map.get("buyFee")));
            data.put("payType", String.valueOf(map.get("settleType")));
            data.put("buyerEname", String.valueOf(map.get("buyUserEname")));
            data.put("buyerName", String.valueOf(map.get("buyUserCname")));
            data.put("buyerId", String.valueOf(map.get("applyId")));//
            data.put("proNo", proNo);//
            //data.put("isMergeBill", String.valueOf(map.get("isMergeBill")));
            if ("1".equals(String.valueOf(map.get("payType")))) {
                getSbmSettleFlow(data, "bailin", String.valueOf(map.get("proId")),
                        String.valueOf(map.get("applyId")), true);
            }
            entity = this.getRpcResult("dealBillIn", data);

            if (null != entity.getEntity()) {
                Map<String, String> resultMap = new HashMap<String, String>();
                resultMap = (Map) entity.getEntity();

                //初始化审核表
                auditInit(proId, "trp_deal", "deal_id", String.valueOf(map.get("dealId")),
                        String.valueOf(paramsMap.get("userEname")),
                        String.valueOf(resultMap.get("processId")), "交易价款流程初始化");
            }
        }
        return entity;
    }

    private void auditInit(String proId, String tableName, String colName, String pid,
            String checkUserEname, String auditFlowProcessId, String taskName) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("pid", pid);
        maps.put("doCode", "auditSave");
        maps.put("tableName", tableName);
        maps.put("colName", colName);
        maps.put("proId", proId);
        maps.put("checkUser", checkUserEname);
        maps.put("methodKey", "init");
        maps.put("taskName", taskName);
        maps.put("auditType", auditFlowProcessId);
        maps.put("sysPass", ConfigUtil.getInstance().interfacePass());
        LoadRpcService.service().doServiceClient("auditService", "auditSave", maps,
                PortalPubFactory.getInstance().getRpcInfo("audit"));
    }

    private void getSbmSettleFlow(Map<String, Object> paramsMap, String transType, String proId,
            String userId, boolean isApply) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("sysPass", ConfigUtil.getInstance().interfacePass());
        data.put("proId", proId);
        data.put("transType", transType);
        if (isApply) {
            data.put("buyerId", userId);
        } else {
            data.put("sellId", userId);
        }
        ResultEntity entity = getRpcResult("settleFlowEntity", data);
        if (null != entity.getEntity()) {
            DataMap apply = (DataMap) entity.getEntity();
            paramsMap.put("sellBankUserName", String.valueOf(apply.get("sellBankUserName")));
            paramsMap.put("sellBankName", String.valueOf(apply.get("sellBankName")));
            paramsMap.put("sellBankNo", String.valueOf(apply.get("sellBankNo")));
            paramsMap.put("sellBankAdr", String.valueOf(apply.get("sellBankAdr")));
            paramsMap.put("settleUserNo", String.valueOf(apply.get("userSettleNo")));
        }
    }

    /**
     * description:  生成价款划出单据
     * params参数说明：
     * proPriceAmount：价款,sellerFeeAmount：转让方服务费
     * sellBankUserName：转让方银行信息,sellBankName：转让方银行信息,sellBankNo：转让方银行信息,sellBankAdr：转让方银行信息
     * settleUserNo:转让方钱包账号,payType:支付方式
     * sellerId:转让方ID,sellerEname:转让方ename, sellerName:转方名称
     * proId,dealId
     */
    private ResultEntity buildBillOut(HttpServletRequest request, Map<String, Object> paramsMap) {
        String proId = String.valueOf(paramsMap.get("proId"));
        DataMap result = null;
        if (ToolsUtil.isNull(proId)) {
            ResultEntity entity = new ResultEntity();
            entity.setResult("false");
            entity.setMessage("缺少方法执行参数");
            return entity;

        }
        String sysPass = ConfigUtil.getInstance().interfacePass();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("sysPass", sysPass);
        data.put("proId", proId);
        String clientIp = RequestTools.getIp(request);
        data.put("Client-IP", clientIp);
        ResultEntity entity = getRpcResult("dealList", data);
        if (null == entity.getEntity()) {
            ResultEntity entity2 = new ResultEntity();
            entity2.setResult("false");
            entity2.setMessage("没有获取到项目成交信息");
            return entity;
        }
        List<Map> list = (List) entity.getEntity();
        for (Map map : list) {///这块需要讨论一下
            data.clear();
            data.put("Client-IP", clientIp);
            data.put("sysPass", sysPass);
            data.put("proId", proId);
            data.put("dealId", String.valueOf(map.get("dealId")));
            data.put("proPriceAmount", String.valueOf(map.get("settlePrice")));
            data.put("sellerFeeAmount", String.valueOf(map.get("sellFee")));
            data.put("payType", String.valueOf(map.get("settleType")));
            data.put("sellerName", String.valueOf(map.get("sellUserCname")));
            data.put("sellerEname", String.valueOf(map.get("sellUserEname")));
            data.put("sellerId", String.valueOf(map.get("sellerId")));
            data.put("payType", String.valueOf(paramsMap.get("payType")));
            if ("0".equals(String.valueOf(paramsMap.get("payType")))) {
                data.put("userSettleNo", String.valueOf(paramsMap.get("userSettleNo")));
            } else {
                data.put("sellBankUserName", String.valueOf(paramsMap.get("sellBankUserName")));
                data.put("sellBankName", String.valueOf(paramsMap.get("sellBankName")));
                data.put("sellBankNo", String.valueOf(paramsMap.get("sellBankNo")));
                data.put("sellBankAdr", String.valueOf(paramsMap.get("sellBankAdr")));
            }
            entity = this.getRpcResult("dealBillOut", data);
        }
        return entity;
    }

    /**
     * description:  保存成交信息
     */
    private ResultEntity saveDeal(HttpServletRequest request, LoginUser loginUser,
            Map<String, Object> paramsMap) {
        paramsMap.put("createUser", loginUser.getUserEname());
        paramsMap.put("operatorUser", loginUser.getUserEname());
        paramsMap.put("orgId", loginUser.getOrgId());
        paramsMap.put("deptId", loginUser.getDeptId());
        paramsMap.put("delStatus", "0");
        paramsMap.put("expStatus", "0");
        paramsMap.put("dealStatus", Validator
                .getDefaultStr(String.valueOf(paramsMap.get("dealStatus")), "10"));//成交提交审核状态
        return getRpcResult("dealSave", paramsMap);
    }

    /**
     * description:  保存成交信息
     */
    private ResultEntity savePro(HttpServletRequest request, LoginUser loginUser,
            Map<String, Object> paramsMap) {
        paramsMap.put("createUser", loginUser.getUserEname());
        paramsMap.put("createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        paramsMap.put("modifyTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        String proStatus = StrUtil.doNull(String.valueOf(paramsMap.get("proStatus")), "0");
        paramsMap.put("proStatus", proStatus);
        paramsMap.put("expStatus", "0");
        System.out.println(StrUtil.doNull(String.valueOf(paramsMap.get("delStatus")), "F"));
        return getRpcResult("proSave", paramsMap);
    }

    /**
     * description:  保存成交信息
     */
    private ResultEntity editPro(HttpServletRequest request, LoginUser loginUser,
            Map<String, Object> paramsMap) {
        paramsMap.put("modifyTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        return getRpcResult("proEdit", paramsMap);
    }

    /**
     * description:  启动项目流程
     */
    private ResultEntity proStartFlow(HttpServletRequest request, LoginUser loginUser,
            Map<String, Object> paramsMap) {
        paramsMap.put("createUser", loginUser.getUserEname());
        paramsMap.put("createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        paramsMap.put("modifyTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        paramsMap.put("proStatus", "10");
        paramsMap.put("expStatus", "0");
        paramsMap.put("opeUserId",
                StrUtil.doNull(String.valueOf(paramsMap.get("opeUserId")), loginUser.getUserId()));
        paramsMap.put("opeUserName", StrUtil.doNull(String.valueOf(paramsMap.get("opeUserName")),
                loginUser.getUserCname()));
        paramsMap.put("opeOrgId",
                StrUtil.doNull(String.valueOf(paramsMap.get("opeOrgId")), loginUser.getOrgId()));
        paramsMap.put("opeDeptId",
                StrUtil.doNull(String.valueOf(paramsMap.get("opeDeptId")), loginUser.getDeptId()));
        return getRpcResult("proStartFlow", paramsMap);
    }

    private ResultEntity getRpcResult(String methodKey, Map<String, Object> params) {
        String beanId = "nytService";//iusService
        if ("dymicSql".equalsIgnoreCase(methodKey)) {
            String dataSource = String.valueOf(params.get("datasource"));
            beanId = PortalPubFactory.getInstance().getBeanId(dataSource);
            return LoadRpcService.service().doServiceClient(beanId, methodKey, params,
                    PortalPubFactory.getInstance().getRpcInfo("ius"));
        } else {
            return LoadRpcService.service().doServiceClient(beanId, methodKey, params,
                    PortalPubFactory.getInstance().getRpcInfo("net"));
        }
    }

    public Map<String, Object> toMapDelNull(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (String key : map.keySet()) {
            if ("class".equals(key))
                continue;
            if (!StrUtil.isNull(String.valueOf(map.get(key))))
                result.put(key, map.get(key));
        }
        return result;
    }

}
